package com.gifts.service.client;

import com.gifts.service.entity.*;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.Map.Entry;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.gifts.service.entity.FacebookUser;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.restfb.Connection;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;

/**
 * 
@author 


**/
public class GoogleShoppingClient {
	
	private static final String KEY="AIzaSyCx2XVRb39tw5UQFxsnTYn_R5db6qoYc_E";	//google shopping api key
	private static final String LINK_DEFAULT="https://www.googleapis.com/shopping/search/v1/public/products?country=US&alt=json";

	GoogleShoppingObj gso=new GoogleShoppingObj();;
	GoogleProduct temp=new GoogleProduct();
	String level="";
	int count=0;
	
	public GoogleShoppingClient(String query) {

		query=query.replace(' ', '+');
		//This part is for filtering for a price range
		//System.out.println("Enter price limit-two numbers");
		//int p1=scanner2.nextInt();
		//int p2=scanner2.nextInt();
		//String url=tq.formalizeQuery(query,p1,p2);
		String url=LINK_DEFAULT+"&key="+KEY+"&q="+query;	//create the url that will be sent to google shopping api
		System.out.println(url);
		
		String response= getHTML(url);	//this html response is in JSON form
		//the rest basically parses the JSON response and creates the GoogleShoppingObj
		final JsonParser parser= new JsonParser();
		//final JsonElement jsonElement = parser.parse(new FileReader("/Users/cagri/Desktop/jsonText.json"));
		final JsonElement jsonElement=parser.parse(response);
		final JsonObject jsonObject=jsonElement.getAsJsonObject();
		traverseJson(jsonObject);

	}
	
	
	public GoogleShoppingClient(String query,Double price1, Double price2) {

		query=query.replace(' ', '+');
		//This part is for filtering for a price range
		//System.out.println("Enter price limit-two numbers");
		//int p1=scanner2.nextInt();
		//int p2=scanner2.nextInt();
		
		String url=null;
		
		if(price1 == null && price2 == null) {
			url=LINK_DEFAULT+"&key="+KEY+"&q="+query;	//create the url that will be sent to google shopping api
		} else {
			url = formalizeQuery(query,price1, price2);
			
		}
		
		System.out.println(url);
		String response= getHTML(url);	//this html response is in JSON form
		//the rest basically parses the JSON response and creates the GoogleShoppingObj
		final JsonParser parser= new JsonParser();
		//final JsonElement jsonElement = parser.parse(new FileReader("/Users/cagri/Desktop/jsonText.json"));
		final JsonElement jsonElement=parser.parse(response);
		final JsonObject jsonObject=jsonElement.getAsJsonObject();
		traverseJson(jsonObject);

	}
	private String formalizeQuery(String q, double price1, double price2){
		  String query=LINK_DEFAULT;
		  String rest="&key="+KEY+"&q="+q+"&restrictBy=price=["+price1+","+price2+"]";

		  return query+rest;
}
	public GoogleShoppingObj getGoogleProducts() 
	{
		return gso;
	}
	public String getHTML(String link){
		String line;
		String result = "";
		try {
			URL url=new URL(link);
			HttpURLConnection conn=(HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
			while ((line=br.readLine())!=null){
				result+=line;
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	public void traverseJson(JsonObject json){

		if (json.has("currentItemCount")){
			gso=new GoogleShoppingObj(json.get("currentItemCount").getAsInt());
		}

		if (json.has("name")){
			temp.setSeller(json.get("name").getAsString());
		}
		if (json.has("title")){
			temp.setTitle(json.get("title").getAsString());
		}
		if (json.has("description"))
			temp.setDescription(json.get("description").getAsString());
		if (json.has("availability"))
			temp.setAvailability(json.get("availability").getAsString().equals("inStock"));
		if (json.has("price"))
			temp.setPrice(json.get("price").getAsDouble());
		if (json.has("shipping"))
			temp.setShipping(json.get("shipping").getAsDouble());
		if (json.has("currency"))
			temp.setCurrency(json.get("currency").getAsString());

		if (json.has("link")){			
			if (level.equals("images")){
				temp.setImageLink(json.get("link").getAsString());
				gso.add(temp);
				temp=new GoogleProduct();
			}
			else{
				temp.setProductLink(json.get("link").getAsString());
			}
		}
		for(final Entry<String, JsonElement> entry: json.entrySet()){
			final String key=entry.getKey();
			level=key;
			final JsonElement value=entry.getValue();

			if (value.isJsonArray()){
				final JsonArray jarr=value.getAsJsonArray();
				for(final JsonElement jobj:jarr){
					if (jobj.isJsonObject())
						traverseJson(jobj.getAsJsonObject());
				}
			}

			else if (value.isJsonObject()){
				traverseJson(value.getAsJsonObject());

			}
		}
	}
}
	
	

	

